package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.PetMapper;
import com.itheima.pojo.PageBean;
import com.itheima.pojo.Pet;
import com.itheima.service.PetService;
import com.itheima.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class PetServiceImp implements PetService {
    @Autowired
    private PetMapper petMapper;
    @Override
    public void add(Pet pet) {
        //补充属性值
        Map<String,Object> map = ThreadLocalUtil.get();
        String userName = (String) map.get("username");
        pet.setCreateUser(userName);
        petMapper.add(pet);
    }

    @Override
    public List<Pet> list() {
        Map<String,Object> map = ThreadLocalUtil.get();
        String userName = (String)map.get("username");
        return petMapper.list(userName);
    }
    @Override
    public PageBean<Pet> all(Integer pageNum, Integer pageSize,String createUser) {
        //1.创建PageBean对象
        PageBean<Pet> pb = new PageBean<>();

        //2.开启分页查询 PageHelper
        PageHelper.startPage(pageNum,pageSize);

        //3.调用mapper
//        Map<String,Object> map = ThreadLocalUtil.get();
//        Integer userId = (Integer) map.get("id");
        List<Pet> as = petMapper.all(createUser);
        //Page中提供了方法，可以获取PageHelper分页查询后，得到的总记录条数和当前页数据
        Page<Pet> p =(Page<Pet>) as;

        //把数据填充到PageBean对象中
        pb.setTotal(p.getTotal());
        pb.setItems(p.getResult());
        return pb;
    }
//    public List<Pet> all() {
////        Map<String,Object> map = ThreadLocalUtil.get();
////        Integer userId = (Integer)map.get("id");
//        return petMapper.all();
//    }

    @Override
    public Pet findById(Integer id) {
        Pet c = petMapper.findById(id);
        return c;
    }
    @Override
    public void update(Pet pet) {
        petMapper.update(pet);

    }
    public  void delete(Pet pet){
        petMapper.delete(pet);
    }

}
